package com.uam.utils;

import com.opencsv.bean.HeaderColumnNameMappingStrategy;
import com.opencsv.exceptions.CsvRequiredFieldEmptyException;
import org.apache.commons.lang3.reflect.FieldUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;

/**
 * @author uam
 * @create 2023/12/4 15:55
 * @email uam@uam.com
 */
public class CustomMappingStrategy<T> extends HeaderColumnNameMappingStrategy<T> {
    private Locale errorLocale = Locale.getDefault();
    public CustomMappingStrategy(Class<? extends T> type){
        super();
        this.setErrorLocale(errorLocale);
        this.setType(type);
    }

    @Override
    public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
        if (this.type == null) {
            throw new IllegalStateException(ResourceBundle.getBundle("opencsv", this.errorLocale).getString("type.before.header"));
        }
        if(headerIndex.isEmpty()) {
            List<String> realHeaderList = loadFieldNames(type);
           // String[] header = realHeaderList.toArray(new String[0]);
            String[] header = {"taskName","airplaneName","startPointName","transitPointsName",
                    "destinationName","startTime","mode","track"};

            // 实际上, 最终 csv 文件的列排序和数据按序获取都去都是通过 headerIndex 对象完成的, 所以这一步针对 header 重新赋值为想要的顺序即可. header 最终会用于初始化 headerIndex
            headerIndex.initializeHeaderIndex(header);
            return header;
        }
        return headerIndex.getHeaderIndex();
    }

    private List<String> loadFieldNames(Class<? extends T> cls) {
        List<String> fieldNames = new ArrayList<>();
        Field[] arr$ = FieldUtils.getAllFields(cls);
        int len$ = arr$.length;
        for(int i$ = 0; i$ < len$; ++i$) {
            Field field = arr$[i$];
            fieldNames.add(field.getName());
        }
        return fieldNames;
    }
}